package yunjiao.javatutorials.lang.concurrent;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * 文件搜索
 *
 * @author yangyunjiao
 */
public class FileSearchTask extends RecursiveTask<List<String>> {
    private final File directory;
    private final String extension;

    public FileSearchTask(File directory, String extension) {
        this.directory = directory;
        this.extension = extension;
    }

    @Override
    protected List<String> compute() {
        List<String> results = new ArrayList<>();
        List<FileSearchTask> subtasks = new ArrayList<>();

        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    // 创建子任务处理子目录
                    FileSearchTask subtask = new FileSearchTask(file, extension);
                    subtask.fork();
                    subtasks.add(subtask);
                } else if (file.getName().endsWith(extension)) {
                    results.add(file.getAbsolutePath());
                }
            }
        }

        // 收集所有子任务的结果
        for (FileSearchTask subtask : subtasks) {
            results.addAll(subtask.join());
        }

        return results;
    }

    public static void main(String[] args) {
        ForkJoinPool pool = new ForkJoinPool();
        FileSearchTask task = new FileSearchTask(new File("D:\\code"), ".java");

        long startTime = System.currentTimeMillis();
        List<String> result = pool.invoke(task);
        long endTime = System.currentTimeMillis();

        System.out.println("并行排序时间: " + (endTime - startTime) + "ms");
        System.out.println("找到 " + result.size() + " 个Java文件:");
//        for (String filePath : result) {
//            System.out.println(filePath);
//        }

        pool.shutdown();
    }
}
